{-
    pHaskell Translator v0.1 
    Copyright (C) 2009  Ruben Marcelo Caro 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-}
module Main where
import IO  
import System.Environment
import LambdaTypes
import Fase1
import Fase2
import GeneratrixRender
   
validName []     = []
validName (x:xs) |x=='.'    = '_':(validName xs)
				 |otherwise =  x:(validName xs)

makePragmaOnce filename =    "#ifndef " ++ (validName filename)
						  ++ "\n#define " ++ (validName filename)
						  ++ "\n#include \"prelude.h\"" ++ "\n\n"


openSecureFile name =   do 
                        openFile name ReadMode
openOutputFile name =   do 
                        openFile name WriteMode

--prelude = "data metalist = metalist a metalist | metaemptylist\n\n"

tanslateFile filename = do
						preludeHandle <- openSecureFile "prelude.phs"
						prelude <- hGetContents preludeHandle
				 		fromHandle  <- openSecureFile filename
				 		lambdaOutHandle <- openOutputFile (filename++".lambda")
				 		outHandle <- openOutputFile (filename++".h")
				 		hPutStr outHandle (makePragmaOnce filename)		 		
						fileContent <- hGetContents fromHandle
						hPutStr lambdaOutHandle ("/*\npHaskell Code: \n\n"++fileContent++"\n*/\n\n\n")
						hPutStr outHandle ("/*\npHaskell Code: \n\n"++fileContent++"\n*/\n\n\n")
						fase1Result <- return (makeFase1 (prelude++"\n"++fileContent))
						--fase1Result <- return (makeFase1 fileContent)
						hPutStr lambdaOutHandle (lambdaPretyPrinterProgram fase1Result)
						hClose lambdaOutHandle
						hPutStr outHandle ("/*\nLambda Abstraction: \n\n"++(lambdaPretyPrinterProgram fase1Result)++"\n*/\n\n\n")
						fase2Result <-  return (makeFase2 fase1Result)
						generatrixes <- return (generatrixRender (prelude++"\n"++fileContent))
						{-putStr fileContent
						putStr (lambdaPretyPrinterProgram fase1Result)
						putStr fase2Result-}
						hPutStr outHandle fase2Result
						hPutStr outHandle ("\n/* GENERATRIX SECTION */\n")
						hPutStr outHandle generatrixes
						hPutStr outHandle ("\n#endif\n")
						putStr "\n\nDone."
						hClose fromHandle
						hClose outHandle
						hClose preludeHandle
									
--Hacerlo mejor con first 
processArgs (x:xs) = tanslateFile x
main  = do
        argv <- getArgs
        processArgs argv
          
